﻿using System;
using System.Net.Mail;
using System.Text;
using System.Timers;

namespace Confcloud.Email
{
	public static class EmailSender
	{
		public static void SetTimerDate(DateTime? date)
		{
			if (date.HasValue)
			{
				DateTime now = DateTime.Now;
				long newStart = (date.Value - now).Ticks/10000;
				newStart = newStart > 0 ? newStart : 100;

				EmailTimer.Interval = EmailTimer.Interval < newStart ? EmailTimer.Interval : newStart;
			}
			else
			{
				EmailTimer.Interval = EmailTimeOut * 60 * 1000;
			}
		}

		public const int EmailTimeOut = 30;

		static readonly Timer EmailTimer = new Timer();

		static EmailSender()
		{
			EmailTimer.Interval = 5*1000;
			EmailTimer.AutoReset = false;
			EmailTimer.Elapsed += EmailTimerElapsed;
			EmailTimer.Enabled = true;
		}

		static void EmailTimerElapsed(object sender, ElapsedEventArgs e)
		{
			EmailTimer.Enabled = false;
			var emailsOnSend = EmailQueue<object>.ReadEmails;
			while (emailsOnSend.Count > 0)
			{
				foreach (Confcloud.Email.EmailQueue q in emailsOnSend)
				{
					try
					{
						MailMessage mm = new MailMessage
						                 	{
																Subject = "=?utf-8?B?" + Convert.ToBase64String(Encoding.UTF8.GetBytes(q.Subject)) + "?=",
						                 		Body = q.Body,
						                 		IsBodyHtml = q.IsHtml,
						                 		From = new MailAddress(/*q.Sender*/"smarly@smarly.net"),
																SubjectEncoding = Encoding.UTF8,
																BodyEncoding = Encoding.UTF8,
						                 	};

						mm.To.Add(new MailAddress(q.Recipient));

						if (!string.IsNullOrWhiteSpace(q.BccRecipient))
							mm.Bcc.Add(q.BccRecipient);

						q.Smtp.SmtpClient.Send(mm);

					}
					catch (Exception ex)
					{
						q.ErrorText = ex.ToString();
					}
					finally
					{
						q.Put();
					}
				}
				emailsOnSend = EmailQueue<object>.ReadEmails;
			}
			EmailTimer.Enabled = true;
		}		 
	}
}